// Package purchase
// @Title purchase[简述该包的主要作用]
// @Description
// @Author  cnHuaShao
// @since v0.0.1
// @Version v1.0.0
// @Date 2024/6/19 22:38
// @Update 2024/6/19 22:38
package purchase

import (
	"FinancialManagement/src/base/baselog"
	"FinancialManagement/src/base/db"
	"fmt"
	"go.uber.org/zap"
)

// GetPurchaseListAll
// @Description: 获取全部采购列表，用于级联选择框使用
// @return data
// @return err
func GetPurchaseListAll() (data string, err error) {
	sql := "SELECT JSON_ARRAYAGG(JSON_OBJECT('code', tt.purchase_vehicle, 'label', tt.purchase_vehicle, 'items',(SELECT JSON_ARRAYAGG(JSON_OBJECT('code', pd2.purchase_id, 'label', pd2.purchase_departuredate)) FROM purchase_detail pd2 WHERE pd2.purchase_vehicle = tt.purchase_vehicle AND pd2.purchase_status = 2 ORDER BY pd2.purchase_id))) FROM (SELECT pd.purchase_vehicle FROM purchase_detail pd WHERE pd.purchase_status = 2 GROUP BY pd.purchase_vehicle ) as tt"
	res := db.Res.DB.GetDbR().Raw(sql).Row()
	err = res.Scan(&data)
	return data, err
}

// GetPurchaseList
// @Description: 获取采购单列表
// @param purchaseVehicle 采购车辆
// @param purchaseUser 采购人
// @param purchaseStatus 采购状态，1暂存，2提交保存，3作废
// @param purchasePaymentStatus 采购单付款状态，1未付款，2部分付款，3全部付款
// @param pageSize
// @param pageNumber
// @return []PurchaseDetail
// @return int64
// @return error
func GetPurchaseList(purchaseDeparture string, purchaseId int, purchaseVehicle, purchaseUser string, purchaseStatus, purchasePaymentStatus, pageSize, pageNumber int) ([]PurchaseDetail, int64, error) {
	var purchaseList []PurchaseDetail
	var count int64
	sqlWhere := " 1=1 "
	if purchaseId != 0 {
		sqlWhere = fmt.Sprintf("%s and purchase_id = %d ", sqlWhere, purchaseId)
	}
	if purchaseVehicle != "" {
		sqlWhere = fmt.Sprintf("%s and purchase_vehicle like '%%%s%%'", sqlWhere, purchaseVehicle)
	}
	// 采购人筛选
	if purchaseUser != "" {
		sqlWhere = fmt.Sprintf("%s and purchase_user like '%%%s%%'", sqlWhere, purchaseUser)
	}
	// 付款状态筛选
	if purchaseStatus != 0 {
		sqlWhere = fmt.Sprintf(" %s and purchase_status = %d", sqlWhere, purchaseStatus)
	} else {
		sqlWhere = fmt.Sprintf(" %s and purchase_status !=3", sqlWhere)
	}
	// 采购单付款状态，1未付款，2部分付款，3全部付款
	if purchasePaymentStatus != 0 {
		sqlWhere = fmt.Sprintf(" %s and purchase_payment_status = %d", sqlWhere, purchasePaymentStatus)
	}
	// 采购发车时间
	if purchaseDeparture != "" {
		sqlWhere = fmt.Sprintf(" %s and purchase_departuredate = '%s'", sqlWhere, purchaseDeparture)
	}

	// 计算起始行
	startPage := (pageNumber - 1) * pageSize
	err := db.Res.DB.GetDbR().Model(&PurchaseDetail{}).Preload("Items").Order("purchase_id desc").Limit(pageSize).Offset(startPage).Where(sqlWhere).Find(&purchaseList).Limit(-1).Offset(-1).Count(&count).Error
	return purchaseList, count, err
}

// CreatePurchaseInfo
// @Description: 创建采购单
// @receiver purchase
// @return error
func (purchase *PurchaseDetail) CreatePurchaseInfo() error {
	err := db.Res.DB.GetDbW().Create(purchase).Error
	return err
}

// GetPurchaseInfo
// @Description: 获取采购明细详情
// @param purchaseId
// @return PurchaseDetail
// @return error
func GetPurchaseInfo(purchaseId int) (PurchaseDetail, error) {
	var purchase PurchaseDetail
	err := db.Res.DB.GetDbR().Where("purchase_id = ?", purchaseId).First(&purchase).Error
	sqlItem := fmt.Sprintf("SELECT pdi.item_id, pdi.purchase_id, pdi.product_id,(SELECT pd.product_name FROM product pd WHERE pd.product_id=pdi.product_id) as productName, pdi.quantity, pdi.price, pdi.total_price, pdi.customer_id,(SELECT ct.name FROM customer ct WHERE ct.customer_id=pdi.customer_id) as customerName, pdi.actual_amount, pdi.item_date, pdi.item_type, pdi.settlement_status, pdi.settlement_amount, pdi.ir_settlement_amount FROM financial.purchase_detail_item AS pdi WHERE pdi.purchase_id=%d",
		purchaseId)
    res, err := db.Res.DB.GetDbR().Raw(sqlItem).Rows()
    if err != nil {
        baselog.Logger.Error("查询采购明细错误", zap.Error(err))
        return purchase, err
    }
    defer res.Close()
    for res.Next() {
        var item PurchaseDetailItem
        err = res.Scan(&item.ItemID, &item.PurchaseID, &item.ProductID, &item.ProductName, &item.Quantity, &item.Price, &item.TotalPrice, &item.CustomerID, &item.CustomerName, &item.ActualAmount, &item.ItemDate, &item.ItemType, &item.SettlementStatus, &item.SettlementAmount, &item.IrSettlementAmount)
        if err != nil {
            baselog.Logger.Error("解析错误", zap.Error(err))
        }
        purchase.Items = append(purchase.Items, item)
    }
    return purchase, err
}

// DeletePurchaseInfo
// @Description: 逻辑删除采购单
// @param purchaseId
// @return error
func DeletePurchaseInfo(purchaseId int) error {
	sql := fmt.Sprintf("update purchase_detail set purchase_status = 3 WHERE purchase_id = %d", purchaseId)
	err := db.Res.DB.GetDbW().Exec(sql).Error
	return err
}

// UpdatePurchaseInfo
// @Description: 修改指定采购单信息
// @receiver purchase
// @return error
func (purchase *PurchaseDetail) UpdatePurchaseInfo() error {
	err := db.Res.DB.GetDbW().Save(purchase).Error
	return err
}

// UpdatePurchaseDetailItem
// @Description: 修改指定采购单明细信息
// @receiver purchaseDetailItem
// @return error
func (purchaseDetailItem *PurchaseDetailItem) UpdatePurchaseDetailItem() error {
	err := db.Res.DB.GetDbW().Save(purchaseDetailItem).Error
	return err
}

// DelPurchaseDetailItem
// @Description: 删除指定采购单明细信息
// @param itemId
// @return error
func DelPurchaseDetailItem(itemId int) error {
	err := db.Res.DB.GetDbW().Delete(&PurchaseDetailItem{}, itemId).Error
	return err
}

// createPurchaseDetailItem
// @Description: 添加新的采购单明细信息
// @receiver purchaseDetailItem
// @return error
func (purchaseDetailItem *PurchaseDetailItem) createPurchaseDetailItem() error {
	err := db.Res.DB.GetDbW().Create(purchaseDetailItem).Error
	return err
}
